import React from 'react'
import './index.css'
import { Layout, Card, Modal, Space, Table, Tabs } from 'antd';
import Draggable from 'react-draggable';
import echarts from 'echarts/lib/echarts'
//导入饼图
import 'echarts/lib/chart/pie'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/title'
import 'echarts/lib/component/legend'
import 'echarts/lib/component/markPoint'
import ReactEcharts from 'echarts-for-react'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import {
    PieChartOutlined,
    DownloadOutlined
} from '@ant-design/icons';

import axios from 'axios';
const { TabPane } = Tabs;
const columns_text = [
    {
        title: '序号',
        dataIndex: 'num',
        key: 'num',
        width: 100
    },
    {
        title: '提交答卷时间',
        dataIndex: 'time',
        key: 'time',
        width: 200
    },
    {
        title: '答案文本',
        dataIndex: 'answer',
        key: 'answer',
    },
];

const data_text = [

];

const columns = [
    {
        title: '选项',
        dataIndex: 'opt',
        key: 'opt',
    },
    {
        title: '小计',
        dataIndex: 'total',
        key: 'total',
    },
    // {
    //     title: '比例',
    //     dataIndex: 'percent',
    //     key: 'percent',
    // },
];

const data = [

];




const { Header, Sider } = Layout;
export default class Content extends React.Component {
    constructor(props) {
        super(props);
        this.getList = this.getList.bind(this);
        this.getTitle = this.getTitle.bind(this);
        this.getModalTitle = this.getModalTitle.bind(this);
        this.LinkToList = this.LinkToList.bind(this);
        this.state = {
            visible_1: false,
            visible_2: false,
            visible_3: false,
            disabled: true,
            bounds: { left: 0, top: 0, bottom: 0, right: 0 },
            q_id: 0,
            title: '',
            data: [],
            data_text: [],
            questions: [{ key: 0, title: '名字', type: 'textarea' }, { key: 1, title: '今天有空吗', type: 'radio' }],
            option: {},
            opt_data: [],
            t_id: 0,
            avg:0
        }
    }
    componentWillMount() {
        let _this = this;
        let value = _this.props.location.state;
        axios.post('/edit', { q_id: value })
            .then(res => {
                if (res.data.success === true) {
                    var json = JSON.parse(res.data.data)
                    console.log(json);
                    _this.setState({
                        q_id :json.q_id,
                        title: json.title,
                        questions: json.questions,
                    })
                }
            })

    }
    showTextModal = (questionIndex) => {
        let _this = this;
        let questions = this.state.questions;
        this.setState({
            t_id: questionIndex,
            data: [],
            opt_data: [],
        })
        axios.post('/showResults', { q_id: _this.state.q_id, t_id: questionIndex })
            .then(res => {
                var json = JSON.parse(res.data.data)
                // let opt_total = json.option;
                let ans = json.textarea;
                console.log(ans);
                ans.map((item, i, array) => {
                    const newDataText = {
                        key: i,
                        num: i + 1,
                        time: item.time,
                        answer: item.text,
                    }
                    this.setState((prevState) => ({
                        data_text: prevState.data.concat(newDataText),
                        // addAreaVisible: false
                    }));
                    console.log(_this.state.data_text);
                })


            })
        this.setState({
            visible_1: true,
        });
    };
    showChooseModal = (questionIndex) => {
        console.log(this.state.q_id);
        let questions = this.state.questions;
        let _this = this;
        this.setState({
            t_id: questionIndex,
            data: [],
            opt_data: [],
            option: {}
        })
        axios.post('/showResults', { q_id: _this.state.q_id, t_id: questionIndex })
            .then(res => {
                var json = JSON.parse(res.data.data)
                let opt_total = json.option;
                console.log(json);
                let opt = questions[questionIndex].options;
                opt.map((item, i, array) => {
                    const newData = {
                        key: i,
                        opt: item.text,
                        total: opt_total[i],
                    }
                    const Data = {
                        name: item.text,
                        value: opt_total[i],
                    }
                    console.log(opt_total[i]);
                    this.setState((prevState) => ({
                        data: prevState.data.concat(newData),
                        opt_data: prevState.opt_data.concat(Data),
                        // addAreaVisible: false
                    }));
                })
                let option = {
                    title: {
                        text: questions[questionIndex].title,
                        x: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: "{a} <br/>{b} : {c} ({d}%)"
                    },
                    // legend: {
                    //     orient: 'vertical',
                    //     top: 20,
                    //     right: 5,
                    //     data: ['是','否']
                    // },
                    series: [
                        {
                            name: '选项人数',
                            type: 'pie',
                            radius: ['30%', '80%'],
                            data: _this.state.opt_data,
                        }
                    ]
                }
                this.setState({
                    option: option,
                });


            })
        this.setState({
            visible_2: true,
        });
    };
    showGradeModal = (questionIndex) => {
        let questions = this.state.questions;
        let _this = this;
        this.setState({
            t_id: questionIndex,
            data: [],
            opt_data: [],
            option: {}
        })
        axios.post('/showResults', { q_id: _this.state.q_id, t_id: questionIndex })
            .then(res => {
                var json = JSON.parse(res.data.data)
                this.setState({
                    avg: json.average_value
                })
                let opt_total = json.option;
                console.log(json);
                let opt = questions[questionIndex].options;
                opt.map((item, i, array) => {
                    const newData = {
                        key: i,
                        opt: item.text,
                        total: opt_total[i],
                    }
                    const Data = {
                        name: item.text,
                        value: opt_total[i],
                    }
                    console.log(opt_total[i]);
                    this.setState((prevState) => ({
                        data: prevState.data.concat(newData),
                        opt_data: prevState.opt_data.concat(Data),
                        // addAreaVisible: false
                    }));
                })
                let option = {
                    title: {
                        text: questions[questionIndex].title,
                        x: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: "{a} <br/>{b} : {c} ({d}%)"
                    },
                    // legend: {
                    //     orient: 'vertical',
                    //     top: 20,
                    //     right: 5,
                    //     data: ['是','否']
                    // },
                    series: [
                        {
                            name: '选项人数',
                            type: 'pie',
                            radius: ['30%', '80%'],
                            data: _this.state.opt_data,
                        }
                    ]
                }
                this.setState({
                    option: option,
                });


            })
        this.setState({
            visible_3: true,
        });
    };
    handleChooseCancel = e => {
        console.log(e);
        this.setState({
            visible_2: false,
        });
    };
    handleGradeCancel = e => {
        console.log(e);
        this.setState({
            visible_3: false,
        });
    };
    handleCancel = e => {
        console.log(e);
        this.setState({
            visible_1: false,
        });
    };
    onStart = (event, uiData) => {
        const { clientWidth, clientHeight } = window?.document?.documentElement;
        const targetRect = this.draggleRef?.current?.getBoundingClientRect();
        this.setState({
            bounds: {
                left: -targetRect?.left + uiData?.x,
                right: clientWidth - (targetRect?.right - uiData?.x),
                top: -targetRect?.top + uiData?.y,
                bottom: clientHeight - (targetRect?.bottom - uiData?.y),
            },
        });
    };
    getTitle(questionIndex) {
        return (
            <div>第{questionIndex + 1}题</div>
        )
    }
    getModalTitle() {
        let questions = this.state.questions;
        return (
            <div>第{this.state.t_id + 1}题:  {questions[this.state.t_id].title}</div>
        )
    }

    callback(key) {
        console.log(key);
    }

    getList() {
        let questions = this.state.questions;
        return questions.map((question, questionIndex, array) => {
            if (question.type === 'radio') {
                return (
                    <div className="card">
                        <Card type="inner" title={this.getTitle(questionIndex)} extra={<span onClick={() => this.showChooseModal(questionIndex)}>查看详细信息</span>}>
                            {question.title}: [单选题]
                        </Card>
                        <Modal title={
                            <div
                                style={{
                                    width: '100%',
                                    cursor: 'move',
                                }}
                                // onMouseOver={() => {
                                //     if (this.state.disabled) {
                                //         this.setState({
                                //             disabled: false,
                                //         });
                                //     }
                                // }}
                                onMouseOut={() => {
                                    this.setState({
                                        disabled: true,
                                    });
                                }}
                                onFocus={() => { }}
                                onBlur={() => { }}

                            >
                                {this.getModalTitle(questionIndex)}
                            </div>
                        }
                            visible={this.state.visible_2}
                            onCancel={this.handleChooseCancel}
                            okButtonProps={{ disabled: true }}
                            cancelButtonProps={{ disabled: true }}
                            footer={null}
                            width={1000}
                            modalRender={modal => (
                                <Draggable
                                    disabled={this.state.disabled}
                                    bounds={this.state.bounds}
                                    onStart={(event, uiData) => this.onStart(event, uiData)}
                                >
                                    <div ref={this.draggleRef}>{modal}</div>
                                </Draggable>
                            )}
                        >
                            <Tabs defaultActiveKey="1" onChange={this.callback}>
                                <TabPane tab="表格" key="1">
                                    <Table
                                        columns={columns}
                                        dataSource={this.state.data}
                                    />
                                </TabPane>
                                <TabPane tab="饼状图" key="2" style={{ textAlign: 'center' }}>
                                    <Card.Grid className="pie_b" style={{ textAlign: 'center', width: 800 }}>
                                        <ReactEcharts option={this.state.option} />
                                    </Card.Grid>
                                </TabPane>
                            </Tabs>


                        </Modal>
                    </div>
                )
            }
            else if (question.type === 'checkbox') {
                return (
                    <div className="card">
                        <Card type="inner" title={this.getTitle(questionIndex)} extra={<span onClick={() => this.showChooseModal(questionIndex)}>查看详细信息</span>}>
                            {question.title}: [多选题]
                        </Card>
                    </div>
                )

            }
            else if (question.type === 'textarea') {
                return (
                    <div className="card">
                        <Card type="inner" title={this.getTitle(questionIndex)} extra={<span onClick={() => this.showTextModal(questionIndex)}>查看详细信息</span>}>
                            {question.title}: [填空题]
                        </Card>
                        <Modal title={
                            <div
                                style={{
                                    width: '100%',
                                    cursor: 'move',
                                }}
                                // onMouseOver={() => {
                                //     if (this.state.disabled) {
                                //         this.setState({
                                //             disabled: false,
                                //         });
                                //     }
                                // }}
                                onMouseOut={() => {
                                    this.setState({
                                        disabled: true,
                                    });
                                }}
                                onFocus={() => { }}
                                onBlur={() => { }}

                            >
                                {this.getModalTitle(questionIndex)}
                            </div>
                        }
                            visible={this.state.visible_1}
                            onCancel={this.handleCancel}
                            okButtonProps={{ disabled: true }}
                            cancelButtonProps={{ disabled: true }}
                            footer={null}
                            width={1000}
                            modalRender={modal => (
                                <Draggable
                                    disabled={this.state.disabled}
                                    bounds={this.state.bounds}
                                    onStart={(event, uiData) => this.onStart(event, uiData)}
                                >
                                    <div ref={this.draggleRef}>{modal}</div>
                                </Draggable>
                            )}
                        >
                            <Table
                                columns={columns_text}
                                pagination={{ position: 'bottomRight', defaultCurrent: 1, defaultPageSize: 10 }}
                                dataSource={this.state.data_text}
                            />

                        </Modal>
                    </div>
                )
            }
            else if (question.type === 'grade') {
                return (
                    <div className="card">
                        <Card type="inner" title={this.getTitle(questionIndex)} extra={<span onClick={() => this.showGradeModal(questionIndex)}>查看详细信息</span>}>
                            {question.title}: [评分题]
                        </Card>
                        <Modal title={
                            <div
                                style={{
                                    width: '100%',
                                    cursor: 'move',
                                }}
                                // onMouseOver={() => {
                                //     if (this.state.disabled) {
                                //         this.setState({
                                //             disabled: false,
                                //         });
                                //     }
                                // }}
                                onMouseOut={() => {
                                    this.setState({
                                        disabled: true,
                                    });
                                }}
                                onFocus={() => { }}
                                onBlur={() => { }}

                            >
                                {this.getModalTitle(questionIndex)}
                            </div>
                        }
                            visible={this.state.visible_3}
                            onCancel={this.handleGradeCancel}
                            okButtonProps={{ disabled: true }}
                            cancelButtonProps={{ disabled: true }}
                            footer={null}
                            width={1000}
                            modalRender={modal => (
                                <Draggable
                                    disabled={this.state.disabled}
                                    bounds={this.state.bounds}
                                    onStart={(event, uiData) => this.onStart(event, uiData)}
                                >
                                    <div ref={this.draggleRef}>{modal}</div>
                                </Draggable>
                            )}
                        >
                            <Tabs defaultActiveKey="1" onChange={this.callback}>
                                <TabPane tab="表格" key="1">
                                    <Table
                                        columns={columns}
                                        dataSource={this.state.data}

                                    />
                                    <div>平均分：{this.state.avg}</div>
                                </TabPane>

                                <TabPane tab="饼状图" key="2" style={{ textAlign: 'center' }}>
                                    <Card.Grid className="pie_b" style={{ textAlign: 'center', width: 800 }}>
                                        <ReactEcharts option={this.state.option} />
                                    </Card.Grid>
                                </TabPane>
                            </Tabs>


                        </Modal>
                    </div>
                )
            }
        })
    }
    LinkToList() {
        let path = {
            pathname: '/list',
            state: this.state.q_id,
        };
            this.props.history.push(path);
    }
    render() {
        return (
            <Layout className="main">
                <Header className="head" style={{ position: 'fixed', zIndex: 1, width: '100%' }}>
                    <div className="logo" />
                    <Link to="/home">
                    <span className="leftest">返回</span></Link>
                    <span className="left" ><PieChartOutlined style={{ marginRight: 5 }} />统计&分析</span>

                        <span className="right" onClick={this.LinkToList}><DownloadOutlined style={{ marginRight: 5 }} />查看下载答卷</span>
 
                </Header>
                <Layout className="site-layout" style={{ marginTop: 60 }}>
                    {this.getList()}
                </Layout>
            </Layout>
        )
    }

}